using System.Windows.Input;
using TeaLightV5.Foundation.BL;
using TeaLightV5.Foundation.Sal.Interfaces;
using TeaLightV5.Foundation.UX.Interfaces.Models;

namespace TeaLightV5.Foundation.UX.ViewModels
{
    public abstract class BaseEntityViewModel<T, TE, TKey>
        : EntityViewModel<TE, TKey>
        where T : IEntityModel<TE, TKey>, new()
        where TE : class, IEntity<TKey>, new()
         
    {

        private readonly ModelParameters<TKey> _parameters;

        private T _data;
        public T Data
        {
            get
            {
                return _data;
            }
            set 
            { 
                _data = value; 
                RaisePropertyChanged("Data"); 
            }
        }

        protected BaseEntityViewModel(ModelParameters<TKey> parameters)
        {
            _parameters = parameters;
            Load();
        }

        private void Load()
        {
            Data = new T();
            TE original = null;
            if (_parameters != null)
            {
                original = Repository.GetById(_parameters.Id);
                if (original != null)
                {
                    Data.SetFrom(original);
                }
            }
            if (original == null)
            {
                Data.SetFrom(new TE());
            }
        }

        public abstract ICommand DeleteCommand { get; }

        public abstract ICommand SaveCommand { get; }

        protected void Delete()
        {
            Repository.Delete(Data.Id);
        }

        protected void Update()
        {
            Repository.Save(Data.GetEntity());
        }

        protected void AddNew()
        {
            Repository.Save(Data.GetEntity());
        }

        public override void ReloadModel()
        {
            Load();
        }
    }
}